package com.smxy.mall.config;

import com.smxy.mall.common.Response;
import com.smxy.mall.model.Auth;
import com.smxy.mall.utils.Token;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 先执行AuthFilter 过滤器， 后执行LoginInterceptor拦截器 ，此时过滤器已解析了token
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getParameter("userId"));
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            response.getWriter().write("缺少token");
            response.setStatus(401);
            return false;
        }else {
            Integer userId = null;
            try {
                userId = Token.getToken(token);
                if(userId!=null && userId!=0 && !StringUtils.isEmpty(userId)){
                    System.out.println("通过拦截器");
                    return true;
                }else{
                    return false;
                }
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
